import store from './store'
import { admin_logout, logout } from './actions'
import { error, warning } from '../api'

/**
 * 异步 action 封装处理
 * @param response
 * @returns {Promise<unknown>}
 */
export function asyncResponseHandler (response) {
  let { code, msg, data } = response
  return new Promise(resolve => {
    if (code === 1) {
      resolve(data)
    } else if (code === 0) {
      error(msg)
    } else if (code === -1) {
      let { $GlobalState: { loginType } } = store.getState()
      warning(msg)
      if (loginType === 'admin') {
        store.dispatch(admin_logout())
      } else if (loginType === 'login') {
        store.dispatch(logout())
      } else {
        store.dispatch(admin_logout())
        store.dispatch(admin_logout())
      }
    }
  })
}